import tkinter as tk
from tkinter import messagebox, ttk
import requests

class RegisterWindow:
    def __init__(self, parent, main_app):
        self.main_app = main_app
        
        self.window = tk.Toplevel(parent)
        self.window.title("用户注册")
        self.window.geometry("500x500")
        self.window.configure(bg='#f0f0f0')
        self.window.transient(parent)
        self.window.grab_set()
        
        self.create_widgets()
    
    def create_widgets(self):
        # 标题
        title_label = tk.Label(
            self.window,
            text="用户注册",
            font=("Arial", 18, "bold"),
            bg='#f0f0f0',
            fg='#2c3e50'
        )
        title_label.pack(pady=20)
        
        # 表单框架
        form_frame = tk.Frame(self.window, bg='#f0f0f0')
        form_frame.pack(pady=10, padx=20, fill='both', expand=True)
        
        # 用户名
        tk.Label(form_frame, text="用户名*:", bg='#f0f0f0', font=("Arial", 12)).grid(row=0, column=0, sticky='e', pady=8, padx=5)
        self.username_entry = tk.Entry(form_frame, font=("Arial", 12), width=25)
        self.username_entry.grid(row=0, column=1, pady=8, padx=5, sticky='w')
        
        # 密码
        tk.Label(form_frame, text="密码*:", bg='#f0f0f0', font=("Arial", 12)).grid(row=1, column=0, sticky='e', pady=8, padx=5)
        self.password_entry = tk.Entry(form_frame, font=("Arial", 12), width=25, show='*')
        self.password_entry.grid(row=1, column=1, pady=8, padx=5, sticky='w')
        
        # 确认密码
        tk.Label(form_frame, text="确认密码*:", bg='#f0f0f0', font=("Arial", 12)).grid(row=2, column=0, sticky='e', pady=8, padx=5)
        self.confirm_password_entry = tk.Entry(form_frame, font=("Arial", 12), width=25, show='*')
        self.confirm_password_entry.grid(row=2, column=1, pady=8, padx=5, sticky='w')
        
        # 姓名
        tk.Label(form_frame, text="姓名*:", bg='#f0f0f0', font=("Arial", 12)).grid(row=3, column=0, sticky='e', pady=8, padx=5)
        self.name_entry = tk.Entry(form_frame, font=("Arial", 12), width=25)
        self.name_entry.grid(row=3, column=1, pady=8, padx=5, sticky='w')
        
        # 手机号
        tk.Label(form_frame, text="手机号*:", bg='#f0f0f0', font=("Arial", 12)).grid(row=4, column=0, sticky='e', pady=8, padx=5)
        self.phone_entry = tk.Entry(form_frame, font=("Arial", 12), width=25)
        self.phone_entry.grid(row=4, column=1, pady=8, padx=5, sticky='w')
        
        # 购车预算
        tk.Label(form_frame, text="购车预算:", bg='#f0f0f0', font=("Arial", 12)).grid(row=5, column=0, sticky='e', pady=8, padx=5)
        self.budget_entry = tk.Entry(form_frame, font=("Arial", 12), width=25)
        self.budget_entry.grid(row=5, column=1, pady=8, padx=5, sticky='w')
        
        # 偏好车型
        tk.Label(form_frame, text="偏好车型:", bg='#f0f0f0', font=("Arial", 12)).grid(row=6, column=0, sticky='e', pady=8, padx=5)
        self.preferred_type_combobox = ttk.Combobox(
            form_frame, 
            values=["SUV", "轿车", "MPV", "跑车", "新能源车", "无特定偏好"],
            font=("Arial", 12),
            width=22,
            state="readonly"
        )
        self.preferred_type_combobox.grid(row=6, column=1, pady=8, padx=5, sticky='w')
        self.preferred_type_combobox.set("无特定偏好")
        
        # 按钮框架
        button_frame = tk.Frame(self.window, bg='#f0f0f0')
        button_frame.pack(pady=20)
        
        # 注册按钮
        register_btn = tk.Button(
            button_frame,
            text="注册",
            command=self.register,
            font=("Arial", 12),
            bg='#2ecc71',
            fg='white',
            width=10
        )
        register_btn.grid(row=0, column=0, padx=10)
        
        # 取消按钮
        cancel_btn = tk.Button(
            button_frame,
            text="取消",
            command=self.window.destroy,
            font=("Arial", 12),
            bg='#95a5a6',
            fg='white',
            width=10
        )
        cancel_btn.grid(row=0, column=1, padx=10)
    
    def register(self):
        # 获取输入数据
        username = self.username_entry.get().strip()
        password = self.password_entry.get().strip()
        confirm_password = self.confirm_password_entry.get().strip()
        name = self.name_entry.get().strip()
        phone = self.phone_entry.get().strip()
        budget = self.budget_entry.get().strip()
        preferred_type = self.preferred_type_combobox.get()
        
        # 验证输入
        if not username or not password or not name or not phone:
            messagebox.showerror("错误", "请填写所有必填字段（标*号）")
            return
        
        if password != confirm_password:
            messagebox.showerror("错误", "两次输入的密码不一致")
            return
        
        if len(password) < 6:
            messagebox.showerror("错误", "密码长度至少6位")
            return
        
        try:
            response = requests.post(
                f"{self.main_app.api_base}/register",
                json={
                    "username": username,
                    "password": password,
                    "name": name,
                    "phone": phone,
                    "budget": float(budget) if budget else None,
                    "preferred_type": preferred_type
                }
            )
            result = response.json()
            
            if result['success']:
                messagebox.showinfo("成功", "注册成功！您获得了100积分奖励")
                self.window.destroy()
            else:
                messagebox.showerror("错误", result['message'])
                
        except requests.exceptions.ConnectionError:
            messagebox.showerror("错误", "无法连接到服务器，请检查后端服务是否启动")
        except Exception as e:
            messagebox.showerror("错误", f"注册失败: {str(e)}")